class_name Gun
extends Node2D



@export var BulletScene: PackedScene
@export var fire_marker: Marker2D

@export var fire_rate: int = 1:
    set(value):
        fire_rate = clampi(value, 1, Settings.MAX_FIRE_RATE)

@export var fire_bullet_count: int = 1:
    set(value):
        fire_bullet_count = clampi(value, 1, int(360 / Settings.NEXT_BULLET_ANGLE))

@export var bullet_radius: float
@export var bullet_damage: int
@export var bullet_speed: float
@export var bullet_knockback_force: int

@onready var bullets: Node2D = get_tree().get_first_node_in_group("bullets")

var _last_fire_time: int = 0
var _bullet_pool: ObjPool = ObjPool.new()



func _ready() -> void:
    _bullet_pool.has_obj_idled.connect(_on_bullet_pool_has_obj_idled)
#    _bullet_pool.create_objs_by_packed_scene(BulletScene, 2000)



func _on_bullet_pool_has_obj_idled(obj: Bullet) -> void:
#    print("linear_velocity: ", obj.linear_velocity)
    obj.sleeping = true
    obj.is_handled = false



func _create_bullet(direction: Vector2) -> void:
    var bullet := BulletScene.instantiate() as Bullet
#    var bullet: Bullet = _bullet_pool.get_obj()
    bullet.global_position = fire_marker.global_position
    bullet.setup(direction, bullet_speed, bullet_damage, bullet_knockback_force, bullet_radius)
    bullets.add_child(bullet)
    bullet.shoot()


func _create_multiple_bullets(direction: Vector2, count: int, angle: float) -> void:
    for i in range(1, count + 1):
        var rotated_direction = direction
        if fire_bullet_count % 2 == 0:
            if i == 1:
                rotated_direction = direction.rotated(deg_to_rad(angle / 2))
            else:
                rotated_direction = direction.rotated(deg_to_rad((i - 1) * angle + angle / 2))
        else:
            rotated_direction = direction.rotated(deg_to_rad(i * angle))
        _create_bullet(rotated_direction)


func fire(direction: Vector2) -> void:
    if Time.get_ticks_msec() - _last_fire_time < 1000.0 / fire_rate:
        return
        
    var half := int(fire_bullet_count / 2)
    # 生成上半子弹
    _create_multiple_bullets(direction, half, 5)
    
    if not fire_bullet_count % 2 == 0:
        _create_bullet(direction)
    
    # 生成下半子弹
    _create_multiple_bullets(direction, half, -5)
    
    _last_fire_time = Time.get_ticks_msec()
